package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<ShoppingCart> selectListById(Long userId) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return shoppingCartMapper.selectList(queryWrapper);
    }

    @Override
    public void saveCart(ShoppingCart shoppingCart) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        if (shoppingCart.getSetmealId() != null) {
            queryWrapper.eq("setmeal_id", shoppingCart.getSetmealId());
        }
        if (shoppingCart.getDishId() != null) {
            queryWrapper.eq("dish_id", shoppingCart.getDishId());
        }
        shoppingCart.setCreateTime(LocalDateTime.now());
        ShoppingCart cart = shoppingCartMapper.selectOne(queryWrapper);
        if (cart == null) {
            shoppingCartMapper.insert(shoppingCart);
        }
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartMapper.updateById(cart);
        }
    }

    @Override
    public void subCart(Long setmealId, Long dishId) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        if (setmealId != null) {
            queryWrapper.eq("setmeal_id", setmealId);
        }
        if (dishId != null) {
            queryWrapper.eq("dish_id", dishId);
        }
        ShoppingCart shoppingCart = shoppingCartMapper.selectOne(queryWrapper);
        if (shoppingCart.getNumber() != 1) {
            shoppingCart.setNumber(shoppingCart.getNumber() - 1);
            shoppingCartMapper.updateById(shoppingCart);
            return;
        }
        shoppingCartMapper.deleteById(shoppingCart.getId());
    }

    @Override
    public void cleanAllCart(Long userId) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        shoppingCartMapper.delete(queryWrapper);
    }


}
